<template>
  <div class="teacher-management-container">
    <el-card class="main-card">
      <!-- 顶部标题和操作按钮 -->
      <div class="header">
        <h2>教师管理面板</h2>
        <div class="actions">
          <el-button type="primary" @click="handleRefresh" plain>
            <el-icon><Refresh /></el-icon> 刷新数据
          </el-button>
        </div>
      </div>

      <!-- 主标签页 -->
      <el-tabs v-model="activeTab" type="card">
        <!-- 论文管理标签页 - 保持不变 -->
        <el-tab-pane label="论文管理" name="paperManagement">
          <div class="tab-content">
            <!-- 论文筛选条件 -->
            <div class="filter-container">
              <el-form :inline="true" :model="paperQuery" class="filter-form">
                <el-form-item label="论文状态">
                  <el-select
                      v-model="paperQuery.status"
                      placeholder="全部状态"
                      clearable
                      style="width: 120px"
                  >
                    <el-option label="全部状态" value="" />
                    <el-option label="草稿" value="DRAFT" />
                    <el-option label="已提交" value="SUBMITTED" />
                    <el-option label="待审核" value="PENDING_REVIEW" />
                    <el-option label="已审核" value="APPROVED" />
                    <el-option label="需修改" value="REVISING" />
                    <el-option label="已拒绝" value="REJECTED" />
                  </el-select>
                </el-form-item>
                <el-form-item label="学生姓名">
                  <el-input
                      v-model="paperQuery.studentName"
                      placeholder="学生姓名"
                      clearable
                      style="width: 180px"
                  />
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="fetchPapers">
                    <el-icon><Search /></el-icon> 搜索
                  </el-button>
                  <el-button @click="resetPaperQuery">
                    <el-icon><Refresh /></el-icon> 重置
                  </el-button>
                </el-form-item>
              </el-form>
            </div>

            <!-- 论文表格 -->
            <el-table
                :data="paperList"
                border
                stripe
                style="width: 100%"
                v-loading="paperLoading"
                height="calc(100vh - 320px)"
                @selection-change="handlePaperSelectionChange"
            >
              <el-table-column type="selection" width="50" align="center" />
              <el-table-column
                  prop="paperId"
                  label="ID"
                  width="80"
                  align="center"
                  sortable
              />
              <el-table-column
                  prop="paperTitle"
                  label="论文标题"
                  min-width="200"
                  show-overflow-tooltip
              />
              <el-table-column
                  prop="studentName"
                  label="学生"
                  width="120"
                  align="center"
              />
              <el-table-column
                  prop="status"
                  label="状态"
                  width="120"
                  align="center"
                  sortable
              >
                <template #default="{ row }">
                  <el-tag
                      :type="getPaperStatusTagType(row.status)"
                      effect="light"
                  >
                    {{ getPaperStatusText(row.status) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column
                  prop="publishDate"
                  label="发表日期"
                  width="120"
                  align="center"
                  :formatter="formatDate"
              />
              <el-table-column
                  prop="submitTime"
                  label="提交时间"
                  width="180"
                  align="center"
                  sortable
                  :formatter="formatDateTime"
              />
              <el-table-column label="操作" width="200" fixed="right" align="center">
                <template #default="{ row }">
                  <el-button
                      size="small"
                      @click="showPaperDetail(row)"
                      :icon="View"
                  >
                    详情
                  </el-button>
                  <el-button
                      size="small"
                      type="primary"
                      @click="showAuditDialog(row)"
                      :disabled="!canAudit(row.status)"
                      :icon="Edit"
                  >
                    审核
                  </el-button>
                </template>
              </el-table-column>
            </el-table>

            <!-- 分页 -->
            <div class="pagination-container">
              <el-pagination
                  v-model:current-page="paperQuery.pageNum"
                  v-model:page-size="paperQuery.pageSize"
                  :total="paperTotal"
                  :page-sizes="[10, 20, 50, 100]"
                  layout="total, sizes, prev, pager, next, jumper"
                  @size-change="fetchPapers"
                  @current-change="fetchPapers"
              />
            </div>
          </div>
        </el-tab-pane>

        <!-- 学生管理标签页 - 从第一段代码整合 -->
        <el-tab-pane label="学生管理" name="studentManagement">
          <div class="tab-content">
            <!-- 学生筛选条件 -->
            <div class="filter-container">
              <el-form :inline="true" :model="studentQuery" class="filter-form">
                <el-form-item label="学生姓名">
                  <el-input
                      v-model="studentQuery.name"
                      placeholder="学生姓名"
                      clearable
                      style="width: 180px"
                  />
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="applyStudentFilter">
                    <el-icon><Search /></el-icon> 搜索
                  </el-button>
                  <el-button @click="resetStudentQuery">
                    <el-icon><Refresh /></el-icon> 重置
                  </el-button>
                </el-form-item>
              </el-form>
              <div class="actions">
                <el-button
                    type="primary"
                    @click="goToAddStudent"
                    icon="Plus"
                >
                  添加学生
                </el-button>
              </div>
            </div>

            <!-- 学生表格 -->
            <el-table
                :data="filteredStudents"
                border
                stripe
                style="width: 100%"
                v-loading="studentLoading"
                height="calc(100vh - 320px)"
                @selection-change="handleStudentSelectionChange"
            >
              <el-table-column type="selection" width="50" align="center" />
              <el-table-column
                  prop="userId"
                  label="ID"
                  width="80"
                  align="center"
                  sortable
              />
              <el-table-column
                  prop="username"
                  label="用户名"
                  width="120"
                  align="center"
              />
              <el-table-column
                  prop="name"
                  label="姓名"
                  width="120"
                  align="center"
              />
              <el-table-column
                  prop="email"
                  label="邮箱"
                  min-width="180"
                  show-overflow-tooltip
              />
              <el-table-column
                  prop="phone"
                  label="电话"
                  width="150"
                  align="center"
              />
              <el-table-column
                  label="状态"
                  width="100"
                  align="center"
                  fixed="right"
              >
                <template #default="{ row }">
                  <el-tag
                      :type="row.status === 1 ? 'success' : 'danger'"
                      effect="light"
                  >
                    {{ row.status === 1 ? '正常' : '禁用' }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column
                  label="操作"
                  width="180"
                  fixed="right"
                  align="center"
              >
                <template #default="{ row }">
                  <el-button
                      size="small"
                      @click="showEditStudentDialog(row)"
                      icon="Edit"
                  >
                    编辑
                  </el-button>
                  <el-button
                      size="small"
                      type="danger"
                      @click="handleRemoveStudent(row.userId)"
                      icon="Delete"
                  >
                    移除
                  </el-button>
                </template>
              </el-table-column>
              <!-- 空数据提示 -->
              <template #empty>
                <div class="empty-state">
                  <el-icon><Empty /></el-icon>
                  <p>暂无学生数据</p>
                </div>
              </template>
            </el-table>

            <!-- 分页 -->
            <div class="pagination-container">
              <el-pagination
                  v-model:current-page="studentQuery.pageNum"
                  v-model:page-size="studentQuery.pageSize"
                  :total="studentTotal"
                  :page-sizes="[10, 20, 50, 100]"
                  layout="total, sizes, prev, pager, next, jumper"
                  @size-change="handlePageSizeChange"
                  @current-change="handlePageChange"
              />
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 论文审核对话框 -->
    <el-dialog
        v-model="auditDialogVisible"
        :title="`论文审核 - ${currentPaper?.paperTitle || '无标题论文'}`"
        width="600px"
    >
      <el-form :model="auditForm" label-width="80px">
        <el-form-item label="审核结果" required>
          <el-radio-group v-model="auditForm.result">
            <el-radio label="APPROVED" border>通过</el-radio>
            <el-radio label="REJECTED" border>拒绝</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="审核意见">
          <el-input
              v-model="auditForm.comment"
              type="textarea"
              :rows="4"
              placeholder="请输入审核意见（选填）"
              show-word-limit
              maxlength="200"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="auditDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitAudit">提交审核</el-button>
      </template>
    </el-dialog>

    <!-- 论文详情对话框 -->
    <el-dialog
        v-model="detailDialogVisible"
        :title="`论文详情 - ${currentPaper?.paperTitle || '无标题论文'}`"
        width="700px"
    >
      <div class="paper-detail">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="论文标题">{{ currentPaper.paperTitle }}</el-descriptions-item>
          <el-descriptions-item label="期刊名称">{{ currentPaper.journal }}</el-descriptions-item>
          <el-descriptions-item label="期号/卷号">
            {{ currentPaper.issue }} / {{ currentPaper.volume }}
          </el-descriptions-item>
          <el-descriptions-item label="页码范围">{{ currentPaper.pageRange }}</el-descriptions-item>
          <el-descriptions-item label="作者列表">
            <div v-for="author in currentPaper.authors" :key="author.order" class="author-item">
              {{ author.order }}. {{ author.name }} ({{ author.affiliation }})
            </div>
          </el-descriptions-item>
          <el-descriptions-item label="第一作者">{{ currentPaper.firstAuthor }}</el-descriptions-item>
          <el-descriptions-item label="通讯作者">{{ currentPaper.correspondingAuthor }}</el-descriptions-item>
          <el-descriptions-item label="发表日期">{{ formatDate(currentPaper.publishDate) }}</el-descriptions-item>
          <el-descriptions-item label="影响因子">{{ currentPaper.impactFactor }}</el-descriptions-item>
          <el-descriptions-item label="论文链接">
            <el-link :href="currentPaper.paperLink" target="_blank" type="primary">
              {{ currentPaper.paperLink }}
            </el-link>
          </el-descriptions-item>
          <el-descriptions-item label="当前状态">
            <el-tag :type="getPaperStatusTagType(currentPaper.status)" effect="light">
              {{ getPaperStatusText(currentPaper.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="提交时间">{{ formatDateTime(currentPaper.submitTime) }}</el-descriptions-item>
        </el-descriptions>
      </div>
      <template #footer>
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 编辑学生对话框 - 从第一段代码整合 -->
    <el-dialog v-model="editStudentDialogVisible" title="编辑学生信息" width="500px">
      <el-form
          :model="editStudentForm"
          label-width="100px"
          :rules="studentRules"
          ref="editStudentFormRef"
      >
        <el-form-item label="用户名">
          <el-input v-model="editStudentForm.username" disabled />
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input
              v-model="editStudentForm.name"
              placeholder="请输入姓名"
          />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input
              v-model="editStudentForm.email"
              placeholder="请输入邮箱"
          />
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input
              v-model="editStudentForm.phone"
              placeholder="请输入电话"
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-switch
              v-model="editStudentForm.status"
              :active-value="1"
              :inactive-value="0"
              active-text="启用"
              inactive-text="禁用"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editStudentDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitEditStudent">保存修改</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Refresh,
  Search,
  View,
  Edit,
  Delete,
  Plus
} from '@element-plus/icons-vue'
import {
  getStudentPapers,
  auditPaper,
  getRelatedStudents,
  updateStudentInfo,
  removeStudentRelation
} from '@/api/teacher.js'
import dayjs from 'dayjs'

const router = useRouter()

// 论文管理状态数据
const activeTab = ref('paperManagement')
const paperList = ref([])
const paperTotal = ref(0)
const paperLoading = ref(false)
const paperQuery = reactive({
  pageNum: 1,
  pageSize: 10,
  status: '',
  studentName: ''
})
const auditDialogVisible = ref(false)
const currentPaper = ref({})
const auditForm = reactive({
  result: 'APPROVED',
  comment: ''
})
const detailDialogVisible = ref(false)

// 学生管理状态数据 - 从第一段代码整合
const studentList = ref([]) // 原始学生数据
const filteredStudents = ref([]) // 筛选后的学生数据
const studentTotal = ref(0)
const studentLoading = ref(false)
const studentQuery = reactive({
  pageNum: 1,
  pageSize: 10,
  name: ''
})
const editStudentDialogVisible = ref(false)
const editStudentFormRef = ref(null)
const editStudentForm = reactive({
  userId: '',
  username: '',
  name: '',
  email: '',
  phone: '',
  status: 1
})
const studentRules = reactive({
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ]
})

// 状态映射配置
const statusConfig = {
  textMap: {
    'DRAFT': '草稿',
    'SUBMITTED': '已提交',
    'APPROVED': '已审核',
    'REVISING': '需修改',
    'REJECTED': '已拒绝',
    'PENDING_REVIEW': '待审核'
  },
  tagTypeMap: {
    'DRAFT': 'info',
    'SUBMITTED': '',
    'APPROVED': 'success',
    'REVISING': 'warning',
    'REJECTED': 'danger',
    'PENDING_REVIEW': 'primary'
  }
}

// 作者数据解析函数
const parseAuthors = (authors) => {
  try {
    if (Array.isArray(authors)) return authors
    if (typeof authors === 'string') return JSON.parse(authors)
    return []
  } catch (e) {
    console.error('作者数据解析失败:', e)
    return []
  }
}

// 表格选择处理
const handlePaperSelectionChange = (selection) => {
  console.log('当前选中行:', selection)
}

// 日期格式化
const formatDate = (row, column, cellValue) => {
  if (!cellValue) return '未设置'
  try {
    const date = dayjs(cellValue.includes('T') ? cellValue.split('T')[0] : cellValue)
    return date.isValid() ? date.format('YYYY-MM-DD') : '无效日期'
  } catch (e) {
    console.warn('日期格式化错误:', e)
    return '日期错误'
  }
}

const formatDateTime = (row, column, cellValue) => {
  if (!cellValue) return '未设置'
  try {
    const date = dayjs(cellValue)
    return date.isValid() ? date.format('YYYY-MM-DD HH:mm:ss') : '无效日期'
  } catch (e) {
    console.warn('日期时间格式化错误:', e)
    return '日期错误'
  }
}

// 状态处理方法
const getPaperStatusText = (status) => {
  return statusConfig.textMap[status] || `未知状态(${status})`
}

const getPaperStatusTagType = (status) => {
  return statusConfig.tagTypeMap[status] || 'info'
}

// 判断是否可以审核
const canAudit = (status) => {
  return ['SUBMITTED', 'PENDING_REVIEW'].includes(status)
}

// 获取论文列表
const fetchPapers = async () => {
  paperLoading.value = true
  try {
    const params = {
      pageNum: paperQuery.pageNum,
      pageSize: paperQuery.pageSize,
      status: paperQuery.status,
      studentName: paperQuery.studentName
    }

    Object.keys(params).forEach(key => {
      if (params[key] === '' || params[key] == null) delete params[key]
    })

    const response = await getStudentPapers(params)
    if (response?.data?.code === 200) {
      const data = response.data.data || {}
      paperList.value = (data.list || []).map(paper => ({
        ...paper,
        authors: parseAuthors(paper.authors)
      }))
      paperTotal.value = data.total || 0
    } else {
      ElMessage.warning(response?.data?.message || '获取论文列表失败')
    }
  } catch (error) {
    console.error('获取论文错误:', error)
    ElMessage.error('获取论文列表失败: ' + (error.message || '未知错误'))
  } finally {
    paperLoading.value = false
  }
}

// 获取学生列表 - 从第一段代码整合
const fetchStudents = async () => {
  studentLoading.value = true
  try {
    const response = await getRelatedStudents()
    let studentData = []

    if (Array.isArray(response)) {
      studentData = response
    } else if (response.data && Array.isArray(response.data)) {
      studentData = response.data
    } else if (response.data?.data && Array.isArray(response.data.data)) {
      studentData = response.data.data
    }

    studentList.value = studentData
    studentTotal.value = studentList.value.length
    studentQuery.pageNum = 1
    applyStudentFilter()
  } catch (error) {
    if (error.response?.status === 401) {
      ElMessage.error('登录已过期，请重新登录')
    } else {
      ElMessage.error('获取学生列表失败: ' + (error.response?.data?.message || error.message))
    }
    console.error('获取学生列表错误:', error)
    studentList.value = []
    studentTotal.value = 0
  } finally {
    studentLoading.value = false
  }
}

// 应用学生筛选条件 - 从第一段代码整合
const applyStudentFilter = () => {
  let result = JSON.parse(JSON.stringify(studentList.value))
  if (studentQuery.name) {
    const searchTerm = studentQuery.name.toLowerCase()
    result = result.filter(student => {
      return (
          (student.name?.toLowerCase() || '').includes(searchTerm) ||
          (student.username?.toLowerCase() || '').includes(searchTerm)
      )
    })
  }
  studentTotal.value = result.length
  const start = (studentQuery.pageNum - 1) * studentQuery.pageSize
  const end = start + studentQuery.pageSize
  filteredStudents.value = result.slice(start, end)
}

// 分页变化处理 - 从第一段代码整合
const handlePageChange = (page) => {
  studentQuery.pageNum = page
  applyStudentFilter()
}

// 每页条数变化处理 - 从第一段代码整合
const handlePageSizeChange = (size) => {
  studentQuery.pageSize = size
  studentQuery.pageNum = 1
  applyStudentFilter()
}

// 显示论文详情
const showPaperDetail = (paper) => {
  currentPaper.value = {
    ...paper,
    authors: parseAuthors(paper.authors)
  }
  detailDialogVisible.value = true
}

// 重置论文查询条件
const resetPaperQuery = () => {
  paperQuery.pageNum = 1
  paperQuery.status = ''
  paperQuery.studentName = ''
  fetchPapers()
}

// 重置学生查询条件 - 从第一段代码整合
const resetStudentQuery = () => {
  studentQuery.pageNum = 1
  studentQuery.name = ''
  applyStudentFilter()
}

// 显示审核对话框
const showAuditDialog = (paper) => {
  currentPaper.value = paper
  auditForm.result = 'APPROVED'
  auditForm.comment = ''
  auditDialogVisible.value = true
}

// 导航到添加学生页面 - 从第一段代码整合
const goToAddStudent = () => {
  router.push({ name: 'AddStudent' })
}

// 显示编辑学生对话框 - 从第一段代码整合
const showEditStudentDialog = (student) => {
  editStudentForm.userId = student.userId || ''
  editStudentForm.username = student.username || ''
  editStudentForm.name = student.name || ''
  editStudentForm.email = student.email || ''
  editStudentForm.phone = student.phone || ''
  editStudentForm.status = student.status || 1
  editStudentDialogVisible.value = true
}

// 提交审核
const submitAudit = async () => {
  if (!currentPaper.value.paperId) {
    ElMessage.error('论文ID不存在')
    return
  }

  try {
    await auditPaper(currentPaper.value.paperId, {
      result: auditForm.result,
      comment: auditForm.comment
    })
    ElMessage.success(auditForm.result === 'APPROVED' ? '论文已通过' : '论文已拒绝')
    auditDialogVisible.value = false
    fetchPapers()
  } catch (error) {
    console.error('审核提交错误:', error)
    ElMessage.error('审核提交失败: ' + (error.message || '未知错误'))
  }
}

// 提交编辑学生 - 从第一段代码整合
const submitEditStudent = async () => {
  try {
    await editStudentFormRef.value?.validate()
    await updateStudentInfo(editStudentForm.userId, {
      name: editStudentForm.name,
      email: editStudentForm.email,
      phone: editStudentForm.phone,
      status: editStudentForm.status
    })
    ElMessage.success('保存成功')
    editStudentDialogVisible.value = false
    fetchStudents()
  } catch (error) {
    if (error !== 'cancel') {
      const errorMsg = error.message || error.response?.data?.message || '保存失败'
      ElMessage.error(errorMsg)
      console.error('编辑学生错误:', error)
    }
  }
}

// 移除学生 - 从第一段代码整合
const handleRemoveStudent = async (id) => {
  try {
    await ElMessageBox.confirm('确定要移除这个学生吗?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    await removeStudentRelation(id)
    ElMessage.success('移除成功')
    fetchStudents()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('移除失败: ' + (error.response?.data?.message || error.message))
      console.error('移除学生错误:', error)
    }
  }
}

// 处理学生选择变化 - 从第一段代码整合
const handleStudentSelectionChange = (selection) => {
  console.log('选中的学生:', selection)
}

// 刷新数据
const handleRefresh = () => {
  fetchPapers()
  fetchStudents()
  ElMessage.success('数据已刷新')
}

// 初始化
onMounted(() => {
  fetchPapers()
  fetchStudents()
})
</script>

<style scoped>
.teacher-management-container {
  padding: 20px;
  height: 100%;
}

.main-card {
  height: 100%;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid var(--el-border-color-light);
}

.filter-container {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
  gap: 10px;
}

.filter-form {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.actions {
  margin-left: 10px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.tab-content {
  padding: 10px 0;
}

.el-table {
  font-size: 14px;
}

.el-table :deep(.el-table__cell) {
  padding: 8px 0;
}

.el-tabs :deep(.el-tabs__header) {
  margin: 0;
}

.el-tabs :deep(.el-tabs__nav-wrap)::after {
  height: 1px;
}

.el-dialog__body {
  padding: 20px;
}

.el-form-item {
  margin-bottom: 18px;
}

.paper-detail {
  padding: 10px;
}

.author-item {
  margin-bottom: 5px;
}

.empty-state {
  padding: 40px 0;
  text-align: center;
  color: var(--el-text-color-secondary);
}

.empty-state :deep(.el-icon) {
  font-size: 24px;
  margin-bottom: 10px;
}
</style>